ZigZag Conversion

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

  1. P A H N
  2. A P L S I I G
  3. Y I R

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

  1. string convert(string text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

Solution:

  1. public class Solution {
  2. public String convert(String s, int nRows) {
  3. if (nRows == 1)
  4. return s;
  5. List<StringBuilder> list = new ArrayList<>();
  6. for (int i = 0; i < nRows; i++) {
  7. list.add(new StringBuilder());
  8. }
  9. int row = 0, dir = 0;
  10. for (int i = 0; i < s.length(); i++) {
  11. list.get(row).append(s.charAt(i));
  12. if (row == 0) dir = 1;
  13. if (row == nRows - 1) dir = -1;
  14. row += dir;
  15. }
  16. StringBuilder res = new StringBuilder();
  17. for (StringBuilder sb : list) {
  18. res.append(sb.toString());
  19. }
  20. return res.toString();
  21. }
  22. }